package com.xjh.him.netty.handler;

import com.xjh.him.domain.UserDO;
import com.xjh.him.netty.HandlerCallback;
import com.xjh.him.netty.NettyCore;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;
import org.xjh.tool.Checks;

@Slf4j
@ChannelHandler.Sharable
public class BaseHandler extends SimpleChannelInboundHandler<Object>
                            implements HandlerCallback {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        log.info("client:{} connected", ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Attribute<UserDO> attribute = ctx.channel().attr(NettyCore.CHANNEL_KEY);
        UserDO userDO = attribute.get();
        if (userDO != null) {
            NettyCore.ACTIVE_USER_CHANNEL.remove(userDO.getId());
            log.info("userId:{} channel remove", userDO.getId());
        }
        log.info("client:{} disconnected", ctx.channel().remoteAddress());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object obj) throws Exception {
        log.info("msg:{}", obj);
        if (!Checks.isEmpty(obj)) {
            Boolean consume = pushConsume(ctx, obj);
            if (!consume) {
                log.error("msg:{} is not consume", obj);
            }
        }else {
            log.error("msg:{} is empty", obj);
        }
    }
}
